﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Configuration;

namespace SynchronizedPlayer {
	/// <summary>
	/// Interaction logic for SettingsWindow.xaml
	/// </summary>
	public partial class SettingsWindow : Window {
		private Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
		private bool changed = false;

		public SettingsWindow() {
			InitializeComponent();

			KeyValueConfigurationCollection settings = config.AppSettings.Settings;
			string[] settingsKeys = settings.AllKeys;
			if (settingsKeys.Contains<string>("IP")) {
				ipTextBox.Text = settings["IP"].Value;
			} else {
				ipTextBox.Text = "192.168.0.0";
			}
			if (settingsKeys.Contains<string>("Port")) {
				portTextBox.Text = settings["Port"].Value;
			} else {
				portTextBox.Text = "23232";
			}
			if (settingsKeys.Contains<string>("MediaFolder")) {
				mediaFolderTextBox.Text = settings["MediaFolder"].Value;
			} else {
				mediaFolderTextBox.Text = "C:\\Music";
			}

			Closing += SettingsWindow_Closing;
			changed = false;
		}

		void SettingsWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
			config.Save(ConfigurationSaveMode.Modified);
			ConfigurationManager.RefreshSection("appSettings");

			if (changed) {
				MessageBox.Show("Changes will be applied after restarting program", "Attention!", MessageBoxButton.OK, MessageBoxImage.Warning);
			}
		}

		private void ipChanged(object sender, TextChangedEventArgs e) {
			changed = true;
			if (config.AppSettings.Settings.AllKeys.Contains<string>("IP")) {
				config.AppSettings.Settings["IP"].Value = ipTextBox.Text;
			} else {
				config.AppSettings.Settings.Add("IP", ipTextBox.Text);
			}
		}

		private void portChanged(object sender, TextChangedEventArgs e) {
			changed = true;
			if (config.AppSettings.Settings.AllKeys.Contains<string>("Port")) {
				config.AppSettings.Settings["Port"].Value = portTextBox.Text;
			} else {
				config.AppSettings.Settings.Add("Port", portTextBox.Text);
			}
		}

		private void mediaFolderChanged(object sender, TextChangedEventArgs e) {
			changed = true;
			if (config.AppSettings.Settings.AllKeys.Contains<string>("MediaFolder")) {
				config.AppSettings.Settings["MediaFolder"].Value = mediaFolderTextBox.Text;
			} else {
				config.AppSettings.Settings.Add("MediaFolder", mediaFolderTextBox.Text);
			}
		}

		private void okClicked(object sender, RoutedEventArgs e) {
			Close();
		}
	}
}
